package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.CarListAdapter;
import com.example.administrator.yanfoxconn.bean.JIMessage;
import com.example.administrator.yanfoxconn.bean.JVSchoolInfo;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.SwipeListViewThree;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 用途：協管 E化放行 車輛查詢
 * Created by Song on 2021/9/8.
 */
public class JMSearchCar extends BaseActivity implements View.OnClickListener {
    private final int MESSAGE_SET_TEXT = 1;//掃描成功賦值
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_UP = 3;//提交信息回復
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤

    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_right)
    Button btnAdd;//新增

    @BindView(R.id.sp_area)
    Spinner spArea;//區域
    @BindView(R.id.et_car)
    EditText etCar;//車牌號
    @BindView(R.id.btn_search)
    Button btnCheck;//查詢
    @BindView(R.id.lv_car)
    ListView listView;

    private CarListAdapter carListAdapter;
    private List<JIMessage> messageList;
    private String[] areaList={"A區","C區","D區","G區","A10","A4","A6","A8"};
    private String area;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jm_search_lv);
        ButterKnife.bind(this);

        tvTitle.setText("查詢界面");
        btnBack.setOnClickListener(this);
        btnCheck.setOnClickListener(this);
        setArea();

    }
    //設置區域下拉菜單的值
    private void setArea(){
        List<String> areaName=new ArrayList<>();
        for (int i = 0;i<areaList.length;i++){
            areaName.add(areaList[i]);
        }
        //稽核課隊下拉列表選擇
        spArea.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, areaName));
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                area=areaName.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_search:
                getList(area,etCar.getText().toString());
                break;
        }
    }

    /**
     * 獲取車輛列表
     * @param area     區域
     * @param carnum   車牌號
     */
    private void getList(String area, String carnum) {

        try {
            String areas = URLEncoder.encode(URLEncoder.encode(area, "UTF-8"), "UTF-8");
            String carnums = URLEncoder.encode(URLEncoder.encode(carnum, "UTF-8"), "UTF-8");
           String url2 = Constants.HTTP_GOODS_EH + "?area=" + areas + "&carnum=" + carnums ;
            showDialog();

            Log.e("---------", "url2==fff===" + url2);
            new Thread() {
                @Override
                public void run() {
                    //把网络访问的代码放在这里
                    String result = HttpUtils.queryStringForPost(url2);
                    dismissDialog();
                    Gson gson = new Gson();
                    if (result != null) {
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            JsonArray array = jsonObject.get("data").getAsJsonArray();
                            messageList = new ArrayList<JIMessage>();

                            for (JsonElement type : array) {
                                JIMessage humi = gson.fromJson(type, JIMessage.class);
                                messageList.add(humi);
                            }
                            Message message = new Message();
                            message.what = MESSAGE_SET_TEXT;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else {
                            Log.e("-----------", "result==" + result);
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    } else {
                        Message message = new Message();
                        message.what = MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }
                }
            }.start();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_TOAST://Toast彈出
                    ToastUtils.showLong(JMSearchCar.this,"成功");
//                    aboutAlert(msg.obj.toString(), MESSAGE_TOAST);
                    break;
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(JMSearchCar.this, R.string.net_mistake);
                    break;
                case MESSAGE_SET_TEXT://進度賦值
                    carListAdapter = new CarListAdapter(JMSearchCar.this,messageList,"jmSearch");
                    listView.setAdapter(carListAdapter);
                    setListViewHeightBasedOnChildren(listView);
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            String areas = null;
                            if (area.equals("A區") || area.equals("C區") || area.equals("D區") || area.equals("G區")) {
                                areas = area.substring(0,1);
                            }else{
                                areas=area;
                            }

                            Intent intent = new Intent(JMSearchCar.this, WebViewActivity.class);
                            intent.putExtra("role", "JMSearch");
                            intent.putExtra("num", messageList.get(position).getHfd());
                            intent.putExtra("area", areas);
                            startActivity(intent);
                        }
                    });
                    break;
            }
            super.handleMessage(msg);
        }
    };
    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     *
     * @param listView
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        CarListAdapter  listAdapter = (CarListAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

}
